package lowlevelcv

import (
	"dustbe/util"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"path"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

func COH(c *gin.Context) {
	ok := util.LimitIpInterval(c, 3)
	if !ok {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "msg": "你请求得太频繁了，过一会儿再来吧！"})
		return
	}

	// 参数 image size guassion_size sigmaX
	size := c.PostForm("size")
	guassion_size := c.PostForm("guassion_size")
	sigmaX := c.PostForm("sigmaX")
	file, _ := c.FormFile("file")
	fileName := file.Filename

	savePath := cachePath + "/" + uuid.New().String() + "-" + fileName
	outPath := cachePath + "/" + uuid.New().String() + "-out-" + fileName
	if err := c.SaveUploadedFile(file, savePath); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "msg": "文件写入服务器磁盘时出错"})
		return
	}

	args := []string{
		savePath,
		outPath,
		size,
		guassion_size,
		sigmaX,
	}

	cmd := exec.Command(cohPath, args...)
	err := cmd.Run()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4004, "msg": "运行错误，错误原因:" + err.Error()})
		return
	}

	imgType := path.Ext(outPath)
	picBytes, _ := ioutil.ReadFile(outPath)
	c.JSON(http.StatusOK, gin.H{"code": 200, "data": gin.H{
		"base64": picBytes,
		"type":   imgType[1:],
	}})
	os.Remove(savePath)
	os.Remove(outPath)
}

func DarkDehaze(c *gin.Context) {
	ok := util.LimitIpInterval(c, 3)
	if !ok {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "msg": "你请求得太频繁了，过一会儿再来吧！"})
		return
	}

	// size w t0
	size := c.PostForm("size")
	w := c.PostForm("w")
	t0 := c.PostForm("t0")
	file, _ := c.FormFile("file")
	fileName := file.Filename

	savePath := cachePath + "/" + uuid.New().String() + "-" + fileName
	outPath := cachePath + "/" + uuid.New().String() + "-out-" + fileName

	if err := c.SaveUploadedFile(file, savePath); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "msg": "文件写入服务器磁盘时出错"})
		return
	}

	args := []string{
		savePath,
		outPath,
		size,
		w,
		t0,
	}

	cmd := exec.Command(dehazePath, args...)
	err := cmd.Run()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4004, "msg": "运行错误，错误原因:" + err.Error()})
		return
	}

	imgType := path.Ext(outPath)
	picBytes, _ := ioutil.ReadFile(outPath)

	c.JSON(http.StatusOK, gin.H{"code": 200, "data": gin.H{
		"base64": picBytes,
		"type":   imgType[1:],
	}})

	os.Remove(savePath)
	os.Remove(outPath)
}
